import { gameState } from './data.js';
import { showAlert } from './utils.js';
import { getActiveCharacter } from './character.js';
import { isActiveCharacter } from './utils.js';
import { Farm } from './farming.js';

// 建筑类
class Building {
    constructor(buildingType, gameState) {
        this.id = `building_${Date.now()}`;
        this.name = buildingType.name;
        this.type = buildingType.id;
        this.landRequired = buildingType.landRequired;
        this.status = '建造中';
        this.progress = 0;
        this.maxProgress = 100;
        this.startDay = gameState.day;
        this.startSeason = gameState.season;
        this.startYear = gameState.year;
    }

    // 更新建筑进度
    updateProgress(progressAmount) {
        this.progress += progressAmount;
        // 检查是否完成建造
        if (this.progress >= this.maxProgress) {
            this.progress = this.maxProgress;
            this.status = '建造完成';
            return true;
        } else {
            return false;
        }
    }

    // 导出建筑数据（用于保存）
    exportData() {
        return {
            id: this.id,
            name: this.name,
            type: this.type,
            landRequired: this.landRequired,
            status: this.status,
            progress: this.progress,
            maxProgress: this.maxProgress,
            startDay: this.startDay,
            startSeason: this.startSeason,
            startYear: this.startYear
        };
    }

    // 从数据导入建筑（用于加载）
    static importData(buildingData) {
        const building = Object.create(Building.prototype);
        Object.assign(building, buildingData);
        return building;
    }
}

// 静态配置 - 所有城市共享
class CityConfig {
    static climateConfig = {
        '温带季风': {
            baseTemperature: 15,
            seasonalTempVariation: 20,
            baseRainfallProbability: 0.3,
            seasonalRainfallAdjustment: {
                '春季': 0.1,
                '夏季': 0.3,
                '秋季': 0.2,
                '冬季': -0.2
            }
        },
        '亚热带季风': {
            baseTemperature: 20,
            seasonalTempVariation: 15,
            baseRainfallProbability: 0.4,
            seasonalRainfallAdjustment: {
                '春季': 0.2,
                '夏季': 0.4,
                '秋季': 0.1,
                '冬季': -0.1
            }
        },
        '热带季风': {
            baseTemperature: 25,
            seasonalTempVariation: 10,
            baseRainfallProbability: 0.5,
            seasonalRainfallAdjustment: {
                '春季': -0.1,
                '夏季': 0.5,
                '秋季': 0.2,
                '冬季': -0.2
            }
        },
        '地中海': {
            baseTemperature: 18,
            seasonalTempVariation: 18,
            baseRainfallProbability: 0.25,
            seasonalRainfallAdjustment: {
                '春季': 0.2,
                '夏季': -0.3,
                '秋季': 0.2,
                '冬季': 0.25
            }
        },
        '温带大陆': {
            baseTemperature: 12,
            seasonalTempVariation: 25,
            baseRainfallProbability: 0.2,
            seasonalRainfallAdjustment: {
                '春季': 0.1,
                '夏季': 0.2,
                '秋季': 0.05,
                '冬季': -0.2
            }
        },
        '温带海洋': {
            baseTemperature: 14,
            seasonalTempVariation: 15,
            baseRainfallProbability: 0.4,
            seasonalRainfallAdjustment: {
                '春季': 0.2,
                '夏季': 0.1,
                '秋季': 0.2,
                '冬季': 0.25
            }
        }
    };

    static weatherTypes = ['晴', '多云', '阴', '小雨', '大雨', '小雪', '大雪'];

    static weatherTransitionMatrix = {
        '晴': { '晴': 0.6, '多云': 0.3, '阴': 0.1, '小雨': 0, '大雨': 0, '小雪': 0, '大雪': 0 },
        '多云': { '晴': 0.3, '多云': 0.5, '阴': 0.2, '小雨': 0, '大雨': 0, '小雪': 0, '大雪': 0 },
        '阴': { '晴': 0.1, '多云': 0.3, '阴': 0.4, '小雨': 0.2, '大雨': 0, '小雪': 0, '大雪': 0 },
        '小雨': { '晴': 0, '多云': 0.1, '阴': 0.3, '小雨': 0.5, '大雨': 0.1, '小雪': 0, '大雪': 0 },
        '大雨': { '晴': 0, '多云': 0, '阴': 0.2, '小雨': 0.6, '大雨': 0.2, '小雪': 0, '大雪': 0 },
        '小雪': { '晴': 0.2, '多云': 0.1, '阴': 0.1, '小雨': 0, '大雨': 0, '小雪': 0.5, '大雪': 0.1 },
        '大雪': { '晴': 0, '多云': 0, '阴': 0.1, '小雨': 0, '大雨': 0, '小雪': 0.3, '大雪': 0.6 }
    };

    static getSeasonalTemperatureAdjustment(season) {
        const adjustments = {
            '春季': 0,
            '夏季': 10,
            '秋季': 0,
            '冬季': -10
        };
        return adjustments[season] || 0;
    }

    static getWeatherTemperatureAdjustment(weather) {
        const adjustments = {
            '晴': 2,
            '多云': 0,
            '阴': -1,
            '小雨': -2,
            '大雨': -3,
            '小雪': -4,
            '大雪': -5
        };
        return adjustments[weather] || 0;
    }
}

// City类 - 每个实例代表一个城市
class City {
    constructor(cityData) {
        this.id = cityData.id || `city_${Date.now()}`;
        this.name = cityData.name || '新城';
        this.climateType = cityData.climateType || '温带季风';
        this.currentWeather = cityData.currentWeather || '晴';
        this.currentTemperature = cityData.currentTemperature || 20;
        this.land = cityData.land || { used: 0, total: 100 };
        this.availableBuildings = cityData.availableBuildings || City.getDefaultAvailableBuildings();
        this.buildings = cityData.buildings ? cityData.buildings.map(buildingData => buildingData) : [];
        this.farm = cityData.farm ? cityData.farm : new Farm(this);
        this.farm.city = this;
    }

    // 获取默认可用建筑列表
    static getDefaultAvailableBuildings() {
        return [
            {
                id: 'warehouse',
                name: '仓库',
                landRequired: 5,
                resources: { 'wood': 10, 'stone': 5 }
            },
            {
                id: 'house',
                name: '住宅',
                landRequired: 3,
                resources: { 'wood': 5, 'stone': 2 }
            }
        ];
    }

    // 更新天气
    updateWeather(season) {
        const currentClimate = CityConfig.climateConfig[this.climateType];
        const seasonalAdjustment = currentClimate.seasonalRainfallAdjustment[season];
        
        // 基于当前天气和概率矩阵更新天气
        const currentWeather = this.currentWeather;
        const probabilities = CityConfig.weatherTransitionMatrix[currentWeather];
        
        let random = Math.random();
        let cumulativeProbability = 0;
        
        for (const [weather, probability] of Object.entries(probabilities)) {
            cumulativeProbability += probability;
            if (random < cumulativeProbability) {
                // 根据温度调整雨雪概率
                const temp = this.currentTemperature;
                if ((weather === '小雪' || weather === '大雪') && temp > 0) {
                    // 如果温度高于0度，雨雪转为雨
                    this.currentWeather = weather === '小雪' ? '小雨' : '大雨';
                } else if ((weather === '小雨' || weather === '大雨') && temp < 0) {
                    // 如果温度低于0度，雨转为雪
                    this.currentWeather = weather === '小雨' ? '小雪' : '大雪';
                } else {
                    this.currentWeather = weather;
                }
                break;
            }
        }
    }

    // 更新温度
    updateTemperature(season) {
        const currentClimate = CityConfig.climateConfig[this.climateType];
        const seasonalAdjustment = CityConfig.getSeasonalTemperatureAdjustment(season);
        
        // 基础温度计算
        const baseTemp = currentClimate.baseTemperature + seasonalAdjustment;
        
        // 添加随机波动
        const dailyVariation = (Math.random() - 0.5) * 10; // -5 到 +5 度的日变化
        
        // 天气影响温度
        const weatherAdjustment = CityConfig.getWeatherTemperatureAdjustment(this.currentWeather);
        
        // 计算最终温度
        this.currentTemperature = Math.round(baseTemp + dailyVariation + weatherAdjustment);
    }

    // 开始建造建筑
    startBuilding(buildingTypeId, character) {
        const buildingType = this.availableBuildings.find(b => b.id === buildingTypeId);
        // 检查资源
        for (const [resourceId, amount] of Object.entries(buildingType.resources)) {
            let itemQuantity = character.getItemQuantity(resourceId);
            if (itemQuantity < amount) {
                return { success: false, message: `资源不足: ${resourceId} 需要 ${amount}，当前只有 ${itemQuantity}` };
            }
        }
        
        // 检查土地
        if (this.land.used + buildingType.landRequired > this.land.total) {
            return { success: false, message: '土地不足' };
        }
        
        // 消耗资源
        for (const [resourceId, amount] of Object.entries(buildingType.resources)) {
            character.removeItem(resourceId, amount);
        }
        
        const newBuilding = new Building(buildingType, gameState); // 使用Building类创建建筑实例
        
        this.buildings.push(newBuilding);
        this.land.used += buildingType.landRequired;
        
        City.increaseConstructionSkill(character, 1); // 执行成功时增加建设技能点
        
        return { success: true, message: `开始建造 ${buildingType.name}`, building: newBuilding };
    }

    
    // 角色执行建筑动作来更新进度
    performBuildingAction(buildingId, character) {
        // 检查角色是否有足够的能量进行建筑工作
        if (character.stamina < 10) {
            return { success: false, message: '角色能量不足，需要至少10点能量' };
        }
        character.stamina -= 10; // 消耗能量
        
        const targetBuilding = this.buildings.find(b => b.id === buildingId);
        if (!targetBuilding) {
            return { success: false, message: '指定的建筑不存在' };
        }
        if (targetBuilding.status !== '建造中') {
            return { success: false, message: '只有建造中的建筑才能执行建筑动作' };
        }
        
        // 计算建筑进度增量
        const constructionSkill = character.skills['建设']?.建筑 || 0;
        const constructionLevel = character.skills['建设']?.level || 1;
        const baseProgress = 5;
        const skillBonus = (constructionSkill * 0.1) + ((constructionLevel - 1) * 1);
        const progressAmount = baseProgress + skillBonus;
            
        targetBuilding.updateProgress(progressAmount); //更新进度
        City.increaseConstructionSkill(character, 1); //提升技能点

        // 刷新UI
        if (isActiveCharacter(character)) {
            this.updateBuildingsList();
        }

        return { success: true, message: `对 ${targetBuilding.name} 进行了建造` };
    }

    // 更新城市信息显示
    updateCityInfoDisplay() {
        document.getElementById('cityName').textContent = this.name;
        document.getElementById('climateType').textContent = this.climateType;
        document.getElementById('currentWeather').textContent = this.currentWeather;
        document.getElementById('currentTemperature').textContent = this.currentTemperature + '°C';
    }

    // 更新建筑列表显示
    updateBuildingsList() {
        const buildingsList = document.getElementById('buildingsList');
        buildingsList.innerHTML = '';
        
        // 创建建筑列表表格
        const buildingTable = document.createElement('table');
        buildingTable.className = 'buildings-table';
        buildingTable.innerHTML = `
            <thead>
                <tr>
                    <th>建筑名称</th>
                    <th>状态</th>
                    <th>占地面积</th>
                    <th>进度</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        `;
        
        const tbody = buildingTable.querySelector('tbody');
        this.buildings.forEach(building => {
            const row = document.createElement('tr');
            const progressText = building.status === '建造中' 
                ? `${Math.floor(building.progress)}%`
                : '100%';
            
            // 只有建造中的建筑显示建造按钮
            const actionButton = building.status === '建造中' 
                ? `<button onclick="performBuildingAction('${building.id}')">建造</button>`
                : '-';
            
            row.innerHTML = `
                <td>${building.name}</td>
                <td>${building.status}</td>
                <td>${building.landRequired}</td>
                <td>${progressText}</td>
                <td>${actionButton}</td>
            `;
            tbody.appendChild(row);
        });
        
        buildingsList.appendChild(buildingTable);
        
        // 显示土地使用情况
        const landInfo = document.createElement('p');
        landInfo.textContent = `土地使用: ${this.land.used} / ${this.land.total} 单位`;
        buildingsList.appendChild(landInfo);
    }

    // 静态方法 - 增加建设技能
    static increaseConstructionSkill(character, points) {
        // 技能增长逻辑，使用角色实例的技能数据
        const baseIncrease = points;
        const talentBonus = character.skills['建设'].talent * 0.1;
        const happinessFactor = character.happiness / 100;
        
        const finalIncrease = baseIncrease * (1 + talentBonus) * happinessFactor;
        
        // 使用角色实例的方法增加技能点
        const levelUpResult = character.increaseSkillPoints('建设', '建筑', finalIncrease);
        
        // 如果有升级，显示升级消息
        if (levelUpResult && levelUpResult.leveledUp && isActiveCharacter(character)) {
            showAlert(levelUpResult.message, character);
        }
    }
    
    // 获取农场信息
    getFarmInfo() {
        return this.farm.getFarmInfo();
    }

    // 添加种植的作物
    addPlantedCrop(crop) {
        this.farm.addPlantedCrop(crop);
    }

    // 获取指定索引的作物
    getPlantedCrop(index) {
        return this.farm.getPlantedCrop(index);
    }

    // 更新作物信息
    updatePlantedCrop(index, updates) {
        return this.farm.updatePlantedCrop(index, updates);
    }

    // 获取所有种植的作物
    getAllPlantedCrops() {
        return this.farm.getAllPlantedCrops();
    }

    // 移除已收获的作物
    removeHarvestedCrops() {
        this.farm.removeHarvestedCrops();
    }
    
    // 更新农场状态
    updateFarm() {
        this.farm.updateIrrigation();
        this.farm.updateFertility();
        this.farm.updateCropGrowth();
    }
}

// 城市管理类 - 管理多个城市实例
class CityManager {
    constructor() {
        this.cities = [];
    }

    // 添加城市
    addCity(cityData) {
        const city = new City(cityData);
        this.cities.push(city);
        return city;
    }

    // 获取当前城市
    getCurrentCity() {
        const activeCharacter = getActiveCharacter();
        return activeCharacter.city;
    }

    // 获取所有城市
    getAllCities() {
        return this.cities;
    }
    
    // 更新所有城市的数据
    updateAllCities() {
        this.cities.forEach(city => {
            console.log('updateAllCities ' + city);
            city.updateWeather(gameState.season);
            city.updateTemperature(gameState.season);
            city.updateFarm();
        });
    }
}

// 创建全局城市管理器实例
const cityManager = new CityManager();

// 初始化城市面板
function initCityPanel() {
    cityManager.getCurrentCity().updateCityInfoDisplay();
    cityManager.getCurrentCity().updateBuildingsList();
    // 动态填充建筑类型选择下拉框
    populateBuildingTypeSelect();
}

// 开始建造建筑
function startBuilding() {
    const currentCity = cityManager.getCurrentCity();
    const activeCharacter = getActiveCharacter();
    const buildingTypeId = document.getElementById('buildingType').value;
    const result = currentCity.startBuilding(buildingTypeId, activeCharacter);
    
    if (result.success) {
        currentCity.updateBuildingsList();
        alert(result.message);
    } else {
        alert(result.message);
    }
}

// 更新天气（全局函数，使用当前城市）
function updateWeather() {
    if (cityManager.getCurrentCity()) {
        cityManager.getCurrentCity().updateWeather(gameState.season);
    }
}

// 更新温度（全局函数，使用当前城市）
function updateTemperature() {
    if (cityManager.getCurrentCity()) {
        cityManager.getCurrentCity().updateTemperature(gameState.season);
    }
}

// 更新建筑列表显示（全局函数，使用当前城市）
function updateBuildingsList() {
    cityManager.getCurrentCity().updateBuildingsList();
}

// 全局函数，供UI按钮调用，执行建筑动作
window.performBuildingAction = function(buildingId) {
    const character = getActiveCharacter();
    const currentCity = cityManager.getCurrentCity();
    const result = currentCity.performBuildingAction(buildingId, character);
        
    if (result.success) {
        updateBuildingsList(); // 更新建筑列表显示
        // 如果需要，也可以更新角色信息显示
        alert(result.message);
    } else {
        // 显示错误信息
        alert(result.error || '执行建筑动作失败');
    }
}

// 更新城市信息显示（全局函数，使用当前城市）
function updateCityInfoDisplay() {
    if (cityManager.getCurrentCity()) {
        cityManager.getCurrentCity().updateCityInfoDisplay();
    }
}

// 动态填充建筑类型选择下拉框
function populateBuildingTypeSelect() {
    const currentCity = cityManager.getCurrentCity();
    const buildingTypeSelect = document.getElementById('buildingType');
    
    if (!currentCity || !buildingTypeSelect) {
        return;
    }
    
    // 清空现有选项
    buildingTypeSelect.innerHTML = '';
    
    // 从城市的availableBuildings动态生成选项
    currentCity.availableBuildings.forEach(building => {
        const option = document.createElement('option');
        option.value = building.id;
        option.textContent = `${building.name} (占地${building.landRequired}单位)`;
        buildingTypeSelect.appendChild(option);
    });
}

// 导出函数和类供其他模块使用
export {
    City,
    Building,
    cityManager,
    updateWeather,
    updateTemperature,
    initCityPanel,
    updateCityInfoDisplay,
    startBuilding,
    updateBuildingsList,
    populateBuildingTypeSelect
};